﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using weixin.api.Jsapi;

namespace weixin.crm
{
    /// <summary>
    /// api 的摘要说明
    /// </summary>
    public class api : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            HttpRequest request = context.Request;

            #region 微信登录
            if (request["Action"] == "wxuserlogin")
            {
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=wxuserlogin&username={0}&password={1}&openid={2}", request["username"], request["password"], request["openid"]));
                JObject json = JObject.Parse(jsonstr);
                if (bool.Parse(json.GetValue("success") + ""))
                {
                    HttpCookie cookies = new HttpCookie("token");
                    cookies.Path = "/";
                    cookies.HttpOnly = true;
                    cookies.Expires = DateTime.Now.AddMonths(1);
                    cookies.Value = json.GetValue("token") + "";
                    context.Response.SetCookie(cookies);

                    cookies = new HttpCookie("driveid");
                    cookies.Path = "/";
                    cookies.HttpOnly = true;
                    cookies.Expires = DateTime.Now.AddMonths(1);
                    cookies.Value = json.GetValue("driveid") + "";
                    context.Response.SetCookie(cookies);
                }
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 打卡
            if (request["Action"] == "sign")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string serverId = request["serverId"];
                string desc = request["remark"];
                if (string.IsNullOrEmpty(serverId))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"图片信息不能为空\"}");
                    return;
                }
                byte[] fileData = weixin.api.Jsapi.weixin_helper.WeiXinGetFile(serverId);
                if (fileData == null)
                {
                    context.Response.Write("{\"success\":false,\"info\":\"下载图片失败\"}");
                    return;
                }
                var url = basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now;
                var formDatas = new List<FormItemModel>();
                formDatas.Add(new FormItemModel()
                {
                    Key = "file1",
                    Value = "",
                    FileName = "file1.jpg",
                    FileContent = fileData
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "Action",
                    Value = "sign"
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "token",
                    Value = token.Value
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "driveid",
                    Value = driveid.Value
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "desc",
                    Value = desc
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "latx",
                    Value = context.Request["latx"]
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "laty",
                    Value = context.Request["laty"]
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "addr",
                    Value = !string.IsNullOrEmpty(request["addr"]) ? request["addr"] : "ios暂时不会反地理编译"
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "iskq",
                    Value = request["iskq"]
                });
                int iskaoqin = 0;
                int.TryParse(request["iskq"], out iskaoqin);
                formDatas.Add(new FormItemModel()
                {
                    Key = "iskaoqin",
                    Value = iskaoqin == 2 ? "1" : "0"
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "kaoqintype",
                    Value = request["kaoqintype"]
                });
                //提交表单
                string result = weixin.api.Jsapi.HttpUtil.PostForm(url, formDatas);
                context.Response.Write(result);
                return;
            }
            #endregion
            #region 获取位置
            if (request["Action"] == "getaddr")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string result = weixin.api.Jsapi.HttpUtil.GetHtmlResponse("https://apis.map.qq.com/ws/geocoder/v1/?location=" + request["lat"] + "," + request["lng"] + "&key=KO7BZ-5JZKD-OK744-PZGY6-N4A36-IHBHR");
                context.Response.Write(result);
                return;
            }
            #endregion
            #region 签到历史记录
            if (request["Action"] == "getsignlist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=getsignlist&token={0}&driveid={1}", token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 打卡机历史记录
            if (request["Action"] == "getdakalist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=getdakalist&token={0}&driveid={1}", token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 其他工作日志
            if (request["Action"] == "matter")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string OtherText = request["matter"];
                if (string.IsNullOrEmpty(OtherText))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"工作内容不能为空\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=matter&token={0}&driveid={1}&OtherText={2}", token.Value, driveid.Value, OtherText));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 客户列表
            if (request["Action"] == "getcustlist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                int page = Math.Max(int.Parse(request["page"]), 1);
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=getcustlist&pagesize=8&page={0}&token={1}&driveid={2}", page, token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 客户联系人列表
            if (request["Action"] == "getlinkmanlist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                int page = Math.Max(int.Parse(request["page"]), 1);
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=getlinklist&pagesize=8&page={0}&token={1}&driveid={2}&cid=" + request["cid"], page, token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 客户跟进
            if (request["Action"] == "follow")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string remark = request["remark"];
                if (string.IsNullOrEmpty(remark))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"洽谈内容不能为空\"}");
                    return;
                }
                if (string.IsNullOrEmpty(request["cid"]) || string.IsNullOrEmpty(request["man"]))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"请选择客户和联系人\"}");
                    return;
                }
                try
                {
                    System.Text.StringBuilder data = new System.Text.StringBuilder();
                    data.AppendFormat("Action=follow&token={0}&driveid={1}", token.Value, driveid.Value);
                    data.AppendFormat("&T_cid={0}", request["cid"]);
                    data.AppendFormat("&T_follow={0}", remark);
                    data.AppendFormat("&T_followtype_val={0}", request["followtype_val"]);
                    data.AppendFormat("&T_followtype={0}", request["followtype"]);
                    data.AppendFormat("&T_sex={0}", request["sex"]);
                    data.AppendFormat("&T_man={0}", request["man"]);
                    data.AppendFormat("&T_post={0}", request["post"]);
                    data.AppendFormat("&T_addr={0}", "");
                    string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", data.ToString());
                    context.Response.Write(jsonstr);
                }
                catch (Exception ex)
                {
                    context.Response.Write("{\"success\":false,\"info\":\"" + ex.Message + "\"}");
                }
                return;
            }
            #endregion
            #region 工作日志记录
            if (request["Action"] == "getworkslist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                //string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain+"/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=getworkslist&token={0}&driveid={1}", "od9r7wH-GKCYPhsT_otM83bgCRqQ084630c70ca785ba0e4618b7fc1a76a3", "279F7A18-39C9-4775-A8F0-1E32C78237EE"));
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=getworkslist&token={0}&driveid={1}", token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 点评工作日志记录
            if (request["Action"] == "postworkslist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=postworkslist&token={0}&driveid={1}&type={2}&id={3}&commt={4}", token.Value, driveid.Value, request["type"], request["id"], request["commt"]));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 跟进方式
            if (request["Action"] == "getfollowtype")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false, \"retry\":true,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=combo&token={0}&driveid={1}", token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 考勤
            if (request["Action"] == "qingjialist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=qingjialist&token={0}&driveid={1}", token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            if (request["Action"] == "jiabanlist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=jiabanlist&token={0}&driveid={1}", token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            if (request["Action"] == "loudakalist")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=loudakalist&token={0}&driveid={1}", token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 员工
            if (request["Action"] == "getpartemp")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=get.partemp.list&type=0&token={0}&driveid={1}", token.Value, driveid.Value));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 申请请假
            if (request["Action"] == "qingjiasave")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                System.Text.StringBuilder data = new System.Text.StringBuilder();
                data.AppendFormat("Action=qingjiasave&");
                data.AppendFormat("token={0}&", token.Value);
                data.AppendFormat("driveid={0}&", driveid.Value);
                data.AppendFormat("reason={0}&", request["reason"]);
                data.AppendFormat("itype={0}&", request["itype"]);
                data.AppendFormat("itypeid={0}&", request["itypeid"]);
                data.AppendFormat("proxy_name={0}&", request["proxy_name"]);
                data.AppendFormat("proxy_id={0}&", request["proxy_id"]);
                data.AppendFormat("times={0}&", request["times"]);
                data.AppendFormat("attach={0}&", request["attach"]);
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", data.ToString());
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 加班单申请
            if (request["Action"] == "jiabansave")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                System.Text.StringBuilder data = new System.Text.StringBuilder();
                data.AppendFormat("Action=jiabansave&");
                data.AppendFormat("token={0}&", token.Value);
                data.AppendFormat("driveid={0}&", driveid.Value);
                data.AppendFormat("reason={0}&", request["reason"]);
                data.AppendFormat("itypeid={0}&", request["itypeid"]);
                data.AppendFormat("itype={0}&", request["itype"]);
                data.AppendFormat("total={0}&", request["total"]);
                data.AppendFormat("hdname={0}&", request["hdname"]);
                data.AppendFormat("employee_id1={0}&", request["employee_id1"]);
                data.AppendFormat("employee_name1={0}&", request["employee_name1"]);
                data.AppendFormat("times={0}&", request["times"]);
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", data.ToString());
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 漏打卡申请
            if (request["Action"] == "loudakasave")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                System.Text.StringBuilder data = new System.Text.StringBuilder();
                data.AppendFormat("Action=loudakasave&");
                data.AppendFormat("token={0}&", token.Value);
                data.AppendFormat("driveid={0}&", driveid.Value);
                data.AppendFormat("reason={0}&", request["reason"]);
                data.AppendFormat("ldate1={0}&", request["ldate1"]);
                data.AppendFormat("morning={0}&", request["morning"]);
                data.AppendFormat("noon={0}&", request["noon"]);
                data.AppendFormat("night={0}&", request["night"]);
                data.AppendFormat("attach={0}&", request["attach"]);
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", data.ToString());
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
            #region 分片上传
            if (request["Action"] == "upload")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string ext = System.IO.Path.GetExtension(request["name"]).ToLower();
                if (!(ext == ".jpeg" || ext == ".jpg" || ext == ".png" || ext == ".bmp" || ext == ".gif"))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"图片格式不正确\"}");
                    return;
                }
                List<byte> fileData = new List<byte>();
                Stream filein = null;
                if (context.Request.Files.Count > 0)
                {
                    filein = context.Request.Files[0].InputStream;
                }
                else
                {
                    filein = context.Request.InputStream;
                }
                byte[] buffer = new byte[10 * 1024];
                int ret = filein.Read(buffer, 0, buffer.Length);
                while (ret > 0)
                {
                    byte[] temp = new byte[ret];
                    Array.Copy(buffer, 0, temp, 0, ret);
                    fileData.AddRange(temp);
                    ret = filein.Read(buffer, 0, buffer.Length);
                }
                var url = basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now;
                var formDatas = new List<FormItemModel>();
                formDatas.Add(new FormItemModel()
                {
                    Key = "file1",
                    Value = "",
                    FileName = request["name"],
                    FileContent = fileData.ToArray()
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "Action",
                    Value = "uploadchunksfile"
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "temppath",
                    Value = request["temppath"]
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "chunk",
                    Value = request["chunk"]
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "chunks",
                    Value = request["chunks"]
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "token",
                    Value = token.Value
                });
                formDatas.Add(new FormItemModel()
                {
                    Key = "driveid",
                    Value = driveid.Value
                });
                //提交表单
                string result = weixin.api.Jsapi.HttpUtil.PostForm(url, formDatas);
                context.Response.Write(result);
                return;
            }
            #endregion
            #region 考勤
            if (request["Action"] == "getuploadchunkssize")
            {
                HttpCookie token = context.Request.Cookies.Get("token");
                HttpCookie driveid = context.Request.Cookies.Get("driveid");
                if (token == null || string.IsNullOrEmpty(token.Value))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"登陆已失效,请重新登录\"}");
                    return;
                }
                string ext = System.IO.Path.GetExtension(request["name"]).ToLower();
                if (!(ext == ".jpeg" || ext == ".jpg" || ext == ".png" || ext == ".bmp" || ext == ".gif"))
                {
                    context.Response.Write("{\"success\":false,\"info\":\"图片格式不正确\"}");
                    return;
                }
                string jsonstr = weixin.api.WXComm.GetHtmlResponse(basepage.Domain + "/api/webapi.ashx?rnd=" + DateTime.Now, "POST", string.Format("Action=getuploadchunkssize&token={0}&driveid={1}&temppath={2}", token.Value, driveid.Value, request["temppath"]));
                context.Response.Write(jsonstr);
                return;
            }
            #endregion
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}